package com.ja.openchat.ui.chat.ext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.annotation.ExtContextMenuItem;
import com.ja.openchat.ui.chat.ext.core.ConversationExt;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.nanchen.compresshelper.CompressHelper;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.VideoParam;
import com.zy.openchat.core.model.video.UploadMedioInfo;
import com.zy.openchat.util.CaptureStrategy;
import com.zy.openchat.util.MediaStoreCompat;
import com.zy.openchat.util.MediaUtils;
import com.zy.openchat.util.compress.util.VideoProgressListener;
import com.zy.openchat.util.glide.GlideApp;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseActivity;


public class CameraExt extends ConversationExt {


    private MediaStoreCompat mediaStoreCompat;

    /**
     * @param containerView 扩展view的container
     * @param conversation
     */
    @ExtContextMenuItem
    public void pickImage(View containerView, ChatInfo conversation) {
        if (mediaStoreCompat == null) {
            mediaStoreCompat = new MediaStoreCompat(activity);

        }
        new XPopup.Builder(activity)
                .asBottomList(null, new String[]{activity.getString(R.string.photograph_text), activity.getString(R.string.video_text)}, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        if (position == 0) {
                            mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true, App.getInstanse().getPackageName() + ".utilcode.fileprovider", Constants.userImagePath()));
                            startActivityForResult(mediaStoreCompat.dispatchCaptureImageIntent(activity), 101);
                        } else {
                            mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true, App.getInstanse().getPackageName() + ".utilcode.fileprovider", Constants.userVideoPath()));
                            startActivityForResult(mediaStoreCompat.dispatchCaptureVideoIntent(activity), 102);
                        }
                    }
                }).show();

    }
    private ProgressDialog progressDialog = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK && mediaStoreCompat != null) {
            if (requestCode == 101) {
                String imagePath = mediaStoreCompat.onActivityResultForImage(data);
                ((BaseActivity)fragment.getActivity()).showProgress();
                Observable.create(new ObservableOnSubscribe<String>() {
                            @Override
                            public void subscribe(@NotNull ObservableEmitter<String> emitter) throws Exception {
                                File newFile = new CompressHelper.Builder(fragment.getContext()).setMaxWidth(1440).setMaxHeight(2880).build().compressToFile(new File(imagePath));
                                emitter.onNext(newFile.getAbsolutePath());
                                emitter.onComplete();
                            }
                        }).subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String first) throws Exception {
                                GlideApp.with(activity)
                                        .asBitmap()
                                        .load(first)
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                //20220811
                                                messageViewModel.sendImgMsg(conversation,first,resource,resource.getWidth(),resource.getHeight());

                                            }
                                        });

                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                ((BaseActivity)fragment.getActivity()).hideProgress();
                                throwable.printStackTrace();
                            }
                        }, new Action() {
                            @Override
                            public void run() throws Exception {
                                ((BaseActivity)fragment.getActivity()).hideProgress();
                            }
                        });

            } else if(requestCode == 102&&data!=null) {
                progressDialog = null;
                String filePath = mediaStoreCompat.onActivityResultForVideo(data);
                VideoParam videoParam = MediaUtils.getVideoParam(filePath);
                if (videoParam.getDuration() > 30) {
                    ToastUtils.showShort("不支持发送超过时长30s的视频");
                    return;
                }
                if(progressDialog==null){
                    progressDialog = new ProgressDialog(fragment.getContext());
                    progressDialog.setTitle(null);
                    progressDialog.setCancelable(false);
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.setMessage(activity.getString(R.string.compressed_video_text));
                    progressDialog.setIndeterminate(false);
                    progressDialog.setMax(10000);
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progressDialog.setProgress(0);
                    progressDialog.show();
                }
                Observable.create(new ObservableOnSubscribe<UploadMedioInfo>() {
                            @Override
                            public void subscribe(@NotNull ObservableEmitter<UploadMedioInfo> emitter) throws Exception {
                                emitter.onNext(UploadMedioInfo.compressVideo(fragment.getActivity(), filePath, new VideoProgressListener() {
                                    UploadMedioInfo compress = UploadMedioInfo.newVideoProgress();
                                    @Override
                                    public void onProgress(float progress) {
                                        compress.videoCompressProgress = progress*10000;
                                        emitter.onNext(compress);
                                    }
                                }));
                                emitter.onComplete();
                            }
                        }).subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<UploadMedioInfo>() {
                            @Override
                            public void accept(UploadMedioInfo first) throws Exception {
                                if(first.isCompressFinish){
                                    messageViewModel.sendVideoMsg(conversation,first.mediaPath,first.duration,first.width,first.height);
                                }else{
                                    if(progressDialog!=null){
                                        progressDialog.setProgress((int)first.videoCompressProgress);
                                    }
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                if(progressDialog!=null){
                                    progressDialog.dismiss();
                                    progressDialog = null;
                                }
                                throwable.printStackTrace();
                            }
                        }, new Action() {
                            @Override
                            public void run() throws Exception {
                                if(progressDialog!=null){
                                    progressDialog.dismiss();
                                    progressDialog = null;
                                }
                            }
                        });
//                if (videoParam != null) {
//                    messageViewModel.sendVideoMsg(conversation, filePath, videoParam.getDuration(), videoParam.getWidth(), videoParam.getHeight());
//                }
            }
        }
    }

    @Override
    public int priority() {
        return 2;
    }

    @Override
    public int iconResId() {
        return R.drawable.icon_camera;
//        return R.mipmap.menu_pictures;
    }

    @Override
    public String title(Context context) {
        return context.getString(R.string.shoot_text);
    }

    @Override
    public String contextMenuTitle(Context context, String tag) {
        return title(context);
    }
}
